'''
fastapi
'''

from fastapi import FastAPI,Request,Depends
from cvv_web import router as upload_router
from admin import router as admin_router,UserInfo,get_current_user
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from typing import Optional

app = FastAPI(title="cvv web", version="1.0.0")

# 包含上传接口路由，可以指定前缀
app.include_router(upload_router, prefix="/api/v1", tags=["文件上传"])

# 包含管理接口路由，也可以指定不同的前缀
app.include_router(admin_router, prefix="/admin", tags=["管理接口"])

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 初始化模板引擎
templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
async def admin_dashboard(request: Request, current_user: Optional[UserInfo] = Depends(get_current_user)):
    """管理后台主页"""
    print(f"Current user: {current_user}")

    if not current_user:
        print("Redirecting to login")
        return templates.TemplateResponse("login.html", {"request": request})

    return templates.TemplateResponse("dashboard.html", {
        "request": request,
        "current_user": current_user
    })

# 登录页面
@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    """登录页面"""
    return templates.TemplateResponse("login.html", {"request": request})


# 用户管理页面
@app.get("/users", response_class=HTMLResponse)
async def users_management(request: Request, current_user: UserInfo = Depends(get_current_user)):
    """用户管理页面"""
    if current_user.user_type != 2:  # 只有管理员可以访问
        return templates.TemplateResponse("error.html", {
            "request": request,
            "error_message": "权限不足"
        })

    return templates.TemplateResponse("users.html", {
        "request": request,
        "current_user": current_user
    })


# 个人资料页面
@app.get("/profile", response_class=HTMLResponse)
async def user_profile(request: Request, current_user: UserInfo = Depends(get_current_user)):
    """个人资料页面"""
    return templates.TemplateResponse("profile.html", {
        "request": request,
        "current_user": current_user
    })

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)